package com.course.auth;

import com.course.domain.enums.Role;
import com.vaadin.navigator.View;
import com.vaadin.spring.access.ViewInstanceAccessControl;
import com.vaadin.ui.UI;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Justin on 2017/5/18.
 */
@Component
public class WebViewAccessControl implements ViewInstanceAccessControl {

    private static final Set<String> ADMIN_VIEWS = new HashSet<String>() {
        {
            add("adminHomeView");
            add("specListView");
            add("specWeekView");
            add("taskListView");
            add("classPlanView");
            add("classTodoView");
            add("classFormView");
            add("classMarkView");
            add("learnStatView");
            add("courseListView");
            add("coursePlanView");
            add("agendaPlanView");
            add("studentListView");
            add("teacherListView");
            add("examInfoView");
        }
    };

    private static final Set<String> TEACHER_VIEWS = new HashSet<String>() {
        {
            add("teacherHomeView");
            add("teacherClassView");
        }
    };

    @Override
    public boolean isAccessGranted(UI ui, String beanName, View view) {
        if (ADMIN_VIEWS.contains(beanName)) {
            return SecurityUtils.hasRole(Role.ADMIN.getName());
        }
        if (TEACHER_VIEWS.contains(beanName)) {
            return SecurityUtils.hasRole(Role.TEACHER.getName());
        }
        return StringUtils.equals("loginView", beanName);
    }
}
